package com.chalk.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author xiaoqiang
 * @Description FileDownload 工具类
 * @date 2018/10/31 10:58
 */
public class FileDownloadUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileDownloadUtil.class);

    /**
     * 文件转换成字节数组
     *
     * @param inputStream 文件输入流
     * @return
     * @throws Exception
     */
    public static byte[] fileToByteArray(InputStream inputStream) throws Exception {
        try {
            byte[] bs = FileCopyUtils.copyToByteArray(inputStream);
            return bs;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 下载文件
     *
     * @param file 文件
     * @return
     * @throws Exception
     */
    public static ResponseEntity<byte[]> fileDownload(File file) throws Exception {
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        String fileName = file.getName();
        byte[] data = FileUtil.toByteArray(file);
        final String userAgent = request.getHeader("USER-AGENT");
        if (StringUtils.isNotBlank(userAgent)) {
            if (StringUtils.contains(userAgent, "Edge")) {//Edge
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (StringUtils.contains(userAgent, "Firefox") || //火狐浏览器
                    StringUtils.contains(userAgent, "Chrome")) { //google
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8"); //其它浏览器
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(data, headers, HttpStatus.OK);
    }

    /**
     * 下载文件
     *
     * @param bs       字节数组
     * @param fileName 文件名,带扩展名
     * @return
     * @throws Exception
     */
    public static ResponseEntity<byte[]> fileDownload(byte[] bs, String fileName) throws Exception {
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        final String userAgent = request.getHeader("USER-AGENT");
        if (StringUtils.isNotBlank(userAgent)) {
            if (StringUtils.contains(userAgent, "Edge")) {//Edge
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (StringUtils.contains(userAgent, "Firefox") || //火狐浏览器
                    StringUtils.contains(userAgent, "Chrome")) { //google
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8"); //其它浏览器
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bs, headers, HttpStatus.OK);
    }

}
